<!DOCTYPE html>
<html>
<head>
    <title>豆包AI聊天</title>
    <meta charset="UTF-8">
    <style>
        body { max-width: 800px; margin: 20px auto; padding: 20px; font-family: Arial, sans-serif; }
        #chatBox { border: 1px solid #ddd; height: 400px; overflow-y: auto; padding: 10px; margin-bottom: 10px; }
        .message { margin: 10px 0; padding: 10px; border-radius: 5px; }
        .user { background: #e3f2fd; margin-left: 20%; }
        .ai { background: #f5f5f5; margin-right: 20%; }
        #inputArea { display: flex; gap: 10px; }
        input { flex: 1; padding: 10px; }
        button { padding: 10px 20px; background: #2196f3; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <h1>豆包AI聊天</h1>
    <div id="chatBox"></div>
    <div id="inputArea">
        <input type="text" id="messageInput" placeholder="输入消息...">
        <button onclick="sendMessage()">发送</button>
        <button onclick="clearHistory()">清除历史</button>
    </div>

    <script>
        let currentSessionId = null;

        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message) return;

            appendMessage('user', message);
            input.value = '';

            try {
                const response = await fetch('http://localhost:8080/api/chat/send', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        message,
                        sessionId: currentSessionId
                    })
                });

                const data = await response.json();
                
                // 保存会话ID
                if (data.sessionId) {
                    currentSessionId = data.sessionId;
                }
                
                appendMessage('ai', data.message);
            } catch (error) {
                appendMessage('ai', '错误: ' + error.message);
            }
        }

        async function clearHistory() {
            if (currentSessionId) {
                await fetch(`http://localhost:8080/api/chat/session/${currentSessionId}`, {
                    method: 'DELETE'
                });
                currentSessionId = null;
                document.getElementById('chatBox').innerHTML = '';
            }
        }

        function appendMessage(type, content) {
            const chatBox = document.getElementById('chatBox');
            const div = document.createElement('div');
            div.className = `message ${type}`;
            div.textContent = content;
            chatBox.appendChild(div);
            chatBox.scrollTop = chatBox.scrollHeight;
        }

        // 回车发送
        document.getElementById('messageInput').addEventListener('keypress', e => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>